<template>
	<view class="page page-block">
		<cl-message ref="message"></cl-message>
		<view class="photo-wrapper">
			<image class="head-img" :src="imgsrc"></image>
		</view>
		<view class="btn-wrapper">
			<view class="ripple-wrapper" @click="click">选择图片
				<span class="ripple" ref="btn"></span>
			</view>
			<view v-if="this.type" class="ripple-wrapper" @click="commit" style="margin-top: 20rpx;">确认修改</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgsrc: "",
				type: false // 标志是否修改头像
			}
		},
		methods: {
			click(e) {
				const query = uni.createSelectorQuery();
				var rect, ripple = this.$refs.btn;
				query.selectAll('.ripple-wrapper').boundingClientRect(data => {
					rect = data[0];
				}).exec();
				ripple.style.height = ripple.style.width = Math.max(rect.width, rect.height) + 'px';
				ripple.classList.remove('show');
				var top = e.changedTouches[0].pageY - rect.top - Math.max(rect.width, rect.height) / 2 - document.body.scrollTop;
				var left = e.changedTouches[0].pageX - rect.left - Math.max(rect.width, rect.height) / 2 - document.body.scrollLeft;
				ripple.style.top = top + 'px'
				ripple.style.left = left + 'px'
				ripple.classList.add('show');
				uni.chooseImage({
					count: 1,
					success: (e) => {
						this.imgsrc = e.tempFilePaths[0];
						this.type = true;
					}
				})
			},
			commit() {
				uni.uploadFile({ // 上传图片
					url: this.$serverUrl + "user/photo",
					filePath: this.imgsrc,
					name: 'photo',
					formData: {
						uid: this.$common.user.uid
					},
					success: (res) => {
						if (res.statusCode == "200") {
							let obj = JSON.parse(res.data);
							if (obj.msg == "ok") {
								this.$refs["message"].open({
									type: 'success',
									message: "图片上传成功",
									duration: 1500,
									iconSize: 24
								});
								this.$common.user.photo = this.$common.photoUrlFormat(obj.data[0] + "?" + new Date().getTime());
								setTimeout(function() {
									uni.redirectTo({
										url: "../userInfo"
									})
								}, 1500)
							} else {
								this.$common.showModal(res.data, false);
							}
						}
					}
				});
			}
		},
		onLoad() {
			if (this.$common.hasLogin) {
				this.imgsrc = this.$common.user.photo;
			}
		}
	}
</script>

<style lang="scss">
	.photo-wrapper {
		display: flex;
		justify-content: center;
		padding: 100rpx 20rpx;
	}

	.head-img {
		width: 700rpx;
		height: 700rpx;
	}

	.btn-wrapper {
		padding: 0 240rpx;
	}

	.btn-wrapper view {
		background-color: $uni-color-primary;
		color: #FFFFFF;
		font-size: 14px;
		border-radius: 0;
		text-align: center;
		padding: 10rpx;
	}
</style>
